package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.script.pojo.dto.MessageSetInitDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.message.factory.MessageSetServiceFactory;
import com.xbongbong.pro.message.service.MessageSetService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 消息推送设置初始化Controller
 *
 * @author LiZhikang
 * @date 2022/11/7 13:58
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/messageSetInit")
public class MessageSetInitController {

    @Resource
    private MessageSetServiceFactory messageSetServiceFactory;

    /**
     * 初始化某一业务
     *
     * @param messageSetInitDTO
     * @param br
     * @return
     */
    @GetMapping("")
    public String init(@Valid MessageSetInitDTO messageSetInitDTO, BindingResult br) {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                MessageSetService abstractMessageSetService = messageSetServiceFactory.getMessageSetService(messageSetInitDTO.getAlias());
                if (Objects.isNull(abstractMessageSetService)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                try {
                    String result = abstractMessageSetService.initSetDetailList();
                    response = new XbbResponse<>(result);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
